package com.pig4cloud.pigx.common.seata.utils;


import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * seata相关工具类
 *
 * @since 2022/9/5 17:40
 */
@Component
public class SeataUtils {

    public static final ThreadLocal<GlobalTransaction> GLOBAL_TX = new ThreadLocal<>();

    /**
     * 开启分布式事务
     *
     * @since 2022/9/5 17:07
     */
    public static void startGlobalTx() {
        if (!Objects.isNull(GLOBAL_TX.get())) {
            return;
        }

        GlobalTransaction globalTx = GlobalTransactionContext.getCurrentOrCreate();

        try {
            globalTx.begin();
        } catch (TransactionException e) {
            throw new RuntimeException(e);
        }

        GLOBAL_TX.set(globalTx);
    }

    /**
     * 提交分布式事务
     *
     * @since 2022/9/5 17:07
     */
    public static void commitGlobalTx() {
        GlobalTransaction globalTx = GLOBAL_TX.get();

        if (Objects.isNull(globalTx)) {
            return;
        }

        try {
            globalTx.commit();
        } catch (TransactionException e) {
            throw new RuntimeException(e);
        }

        GLOBAL_TX.remove();
    }

    /**
     * 回滚分布式事务
     *
     * @since 2022/9/5 17:07
     */
    public static void rollbackGlobalTx() {
        GlobalTransaction globalTx = GLOBAL_TX.get();

        if (Objects.isNull(globalTx)) {
            return;
        }

        try {
            globalTx.rollback();
        } catch (TransactionException e) {
            throw new RuntimeException(e);
        }

        GLOBAL_TX.remove();
    }
}
